package cn.restcloud.springboot.config;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
//import cn.restcloud.example.ssofilter.SSOLoginFilter;
import cn.restcloud.framework.core.cache.CacheFactory;
import cn.restcloud.framework.core.util.ConfigUtil;
import cn.restcloud.framework.filters.ServiceFilter;
import cn.restcloud.springboot.init.RestCloudGatewayServlet;
import cn.restcloud.springboot.init.RestCloudServlet;
import cn.restcloud.springboot.init.TestPerformanceServlet;

@Configuration
public class SpringbootWebMvcConfig extends WebMvcConfigurationSupport{
	private static String rootPath=null;
	private static String gatewayRootPath=null;
	
	//rest服务的根目录
	public static String getRootPath() {
		if(rootPath!=null) {return rootPath;}
		rootPath=ConfigUtil.getLocalConfig("api.root.path","/restcloud");
		return rootPath;
	}
	
	//网关服务的根目录 /gateway
	public static String getGatewayRootPath() {
		if(gatewayRootPath!=null) {return gatewayRootPath;}
		gatewayRootPath=ConfigUtil.getLocalConfig("gateway.root.path","/gateway");
		return gatewayRootPath;
	}

	
	@Bean
	public ServletRegistrationBean<RestCloudServlet> servletRegistrationActionBean() {
		//restcloud api 拦截
		String mapUrl= getRootPath();
		if(!mapUrl.equals("/")) {mapUrl= mapUrl+"/*";}
		ServletRegistrationBean<RestCloudServlet> registrationBean=new ServletRegistrationBean<RestCloudServlet>(new RestCloudServlet(), mapUrl);
		registrationBean.setAsyncSupported(true); //设置为支持异步处理
		registrationBean.setName("RestCloudAPIDispatcher");
		return registrationBean;
	}
	
	@Bean
	public ServletRegistrationBean<RestCloudGatewayServlet> servletRegistrationGatewayBean() {
		//网关api拦截
		String mapUrl= getGatewayRootPath();
		if(!mapUrl.equals("/")) {mapUrl= mapUrl+"/*";}
		ServletRegistrationBean<RestCloudGatewayServlet> registrationBean=new ServletRegistrationBean<RestCloudGatewayServlet>(new RestCloudGatewayServlet(), mapUrl);
		HashMap<String,String> params=new HashMap<String,String>();
		try {
			String catchRootPath=getGatewayRootPath();
			if(catchRootPath.equals("/")) {catchRootPath=null;} //要设为null值
			CacheFactory.put(CacheFactory.DefaultCache, "GatewayRootPath", catchRootPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		registrationBean.setAsyncSupported(true); //设置为支持异步处理
		registrationBean.setInitParameters(params);
		registrationBean.setName("GatewayRouterDispatcher");
		return registrationBean;
	}
	
    //用来像监控中心Dashboard发送stream信息
    @Bean
    public ServletRegistrationBean<HystrixMetricsStreamServlet> hystrixMetricsStreamServlet() {
        ServletRegistrationBean<HystrixMetricsStreamServlet> registration = new ServletRegistrationBean<HystrixMetricsStreamServlet>(new HystrixMetricsStreamServlet());
        registration.addUrlMappings("/restcloud/hystrix.stream");
        return registration;
    }
	
	@Bean
	public ServletRegistrationBean<TestPerformanceServlet> servletRegistrationTestPerformanceBean() {
		//restcloud 性能url拦截
		String mapUrl="/performance/test";
		ServletRegistrationBean<TestPerformanceServlet> registrationBean=new ServletRegistrationBean<TestPerformanceServlet>(new TestPerformanceServlet(), mapUrl);
		registrationBean.setAsyncSupported(true); //设置为支持异步处理
		registrationBean.setName("TestPerformanceServlet");
		return registrationBean;
	}
	
    @Override    
    public void addInterceptors(InterceptorRegistry registry) {    
        //registry.addInterceptor(new RestCloudInterceptor()).addPathPatterns("/**").excludePathPatterns(SpringbootApplication.rootPath+"/*");    
    }
    
	@Bean
	public HttpMessageConverter<String> responseBodyConverter() {
		//解决springboot输出消息中文乱码问题
	    StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
	    return converter;
	}
	
    @Bean  
    public FilterRegistrationBean<ServiceFilter> filterRegistration() {
	   //解决跨域问题
        FilterRegistrationBean<ServiceFilter> registration = new FilterRegistrationBean<ServiceFilter>();  
        registration.setFilter(new ServiceFilter());  
        registration.addUrlPatterns("/*");
        registration.setName("serviceFilter");  
        registration.setOrder(1);  
        return registration;
    }
    
	@Override 
	public void addResourceHandlers(ResourceHandlerRegistry registry) { 
		  //设置资源路径.如果在application.properties中指定了ResourceLocationPath的路径，则所有res目录中的目录和文件必须放到此目录下
	      registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
	      registry.addResourceHandler("/**/favicon.ico").addResourceLocations("classpath:/static/");
	      String resourceLocationPath=ConfigUtil.getLocalConfig("ResourceLocationPath"); //资源文件所在路径
	      if(StringUtils.isNotBlank(resourceLocationPath)){
	    	  if(!resourceLocationPath.endsWith("/")){resourceLocationPath+="/";} //增加一个/符号
	    	  registry.addResourceHandler("/res/**").addResourceLocations("file:"+resourceLocationPath); //指定资源文件路径
	      }
	      registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		  super.addResourceHandlers(registry);
	}
	
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
	    super.configureMessageConverters(converters);
	    converters.add(responseBodyConverter());
	    converters.add(new MappingJackson2HttpMessageConverter()); //解决No converter found for return value of type: class java.util.LinkedHashMap
	}
	
}
